<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElTable, ElMessageBox } from "element-plus";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
import { getLoginlogListApi, deleteLoginlogApi, batchDeleteLoginlogApi, LoginLogModel } from "@/api/syslog/loginlog";
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
import { useI18n } from "vue-i18n";
defineOptions({
  name: "loginlog"
});

const i18n = useI18n();
const { t } = i18n;
const pageSizeOps = ref(pageSizeOptions)
// 搜索参数
const searchParams = ref({
  loginName:"",
  ipAddr:"",
  timeRange: [],
  pageSize: 100,
  page: 1,
});
// 搜索字段配置
const searchFields = ref([
  {
    prop: "loginName",
    name: t("syslog.loginlog.userName"),
    type: "input",
    placeholder: "",
  },
  {
    prop: "ipAddr",
    name: t("syslog.loginlog.ipAddress"),
    type: "input",
    placeholder: "",
  },
  {
    prop: 'timeRange',
    name: t("buttons.timeRange"),
    type: 'datetimeRange',
    clearable: true,
    isHidden: false,
  },
]);

// 表格数据
const tableData = ref<LoginLogModel[]>([]);
const total = ref(0);
const loading = ref(false);

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const response = await getLoginlogListApi({
      ...searchParams.value
    });

    if (response.code === 0) {
      tableData.value = response.data?.list || [];
      total.value = response.data?.total || 0;
    } else {
      ElMessage.error(response.msg || t('syslog.loginlog.getFailed'));
    }
  } catch (error) {
    total.value = 0;
    ElMessage.error(t('syslog.loginlog.getFailed'));
  } finally {
    loading.value = false;
  }
};

// 初始加载
onMounted(() => {
  loadData();
});

// 分页变化处理
const handlePaginationSizeChange = (pageSize: number) => {
  searchParams.value.pageSize = pageSize;
  loadData();
};
const handlePaginationPageChange = (page: number) => {
  searchParams.value.page = page;
  loadData();
};

// 删除操作
const handleDelete = async (infoId: number) => {
  try {
    await ElMessageBox.confirm(t('syslog.loginlog.deleteConfirm'), t('buttons.confirm'), {
      confirmButtonText: t('buttons.confirm'),
      cancelButtonText: t('buttons.cancel'),
      type: 'warning'
    });

    const response = await deleteLoginlogApi(infoId);
    if (response.code === 0) {
      ElMessage.success(t('syslog.loginlog.deleteSuccess'));
      await loadData();
    } else {
      ElMessage.error(response.msg || t('syslog.loginlog.deleteFailed'));
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('syslog.loginlog.deleteFailed'));
    }
  }
};

// 批量删除
const selectedRows = ref<LoginLogModel[]>([]);

const handleSelectionChange = (rows: LoginLogModel[]) => {
  selectedRows.value = rows;
};

const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning(t('syslog.loginlog.selectRecordFirst'));
    return;
  }

  try {
    await ElMessageBox.confirm(
      t('syslog.loginlog.batchDeleteConfirm', { count: selectedRows.value.length }),
      t('buttons.confirm'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning'
      }
    );

    const infoIds = selectedRows.value.map(row => row.infoId);
    const response = await batchDeleteLoginlogApi(infoIds);
    if (response.code === 0) {
      ElMessage.success(t('syslog.loginlog.batchDeleteSuccess'));
      await loadData();
      selectedRows.value = [];
    } else {
      ElMessage.error(response.msg || t('syslog.loginlog.batchDeleteFailed'));
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('syslog.loginlog.batchDeleteFailed'));
    }
  }
};

// 格式化状态显示
const formatStatus = (status: number) => {
  return status === 0 ? t('syslog.loginlog.success') : t('syslog.loginlog.fail');
};

const  handleChange = (e: any) => {
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
}
const handleSearch = async (e:any) => {
  searchParams.value.page = 1
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  await  loadData();
}
const handleReset = (e:any) => {
}

</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <Searchbox
          :fields= searchFields
          :initialValues="searchParams"
          :maxVisibleFields=10
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>

    <div class="button-area">
      <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
        {{ t("buttons.batchDelete") }}
      </el-button>
    </div>

    <el-table
      :data="tableData"
      v-loading="loading"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
<!--      <el-table-column prop="infoId" :label="t('syslog.loginlog.logId')" width="120" />-->
      <el-table-column prop="loginName" :label="t('syslog.loginlog.userName')" width="120" />
      <el-table-column prop="ipaddr" :label="t('syslog.loginlog.ipAddress')" width="150" />
      <el-table-column prop="loginLocation" :label="t('syslog.loginlog.loginLocation')" />
      <el-table-column prop="browser" :label="t('syslog.loginlog.browser')" width="120" />
      <el-table-column prop="os" :label="t('syslog.loginlog.os')" width="120" />
      <el-table-column prop="status" :label="t('syslog.loginlog.loginStatus')" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 0 ? 'success' : 'danger'">
            {{ formatStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="msg" :label="t('syslog.loginlog.loginInfo')" />
      <el-table-column prop="loginTime" :label="t('syslog.loginlog.loginTime')" width="180" />
      <el-table-column :label="t('syslog.loginlog.operation')" width="120">
        <template #default="{ row }">
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row.infoId)"
          >
            {{ t("buttons.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="searchParams.page"
      v-model:page-size="searchParams.pageSize"
      :page-sizes="pageSizeOps"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handlePaginationSizeChange"
      @current-change="handlePaginationPageChange"
    />
  </el-card>
</template>

<style scoped lang="scss">
.button-area {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-start;
}

//.card-header {
//  display: flex;
//  align-items: center;
//  justify-content: stretch;
//  width: 100%;
//}
</style>
